from . import api_blueprint
from flask import request, json
from app import db
from app.model.message import Message
import time


@api_blueprint.route('/message/all', methods=['GET'])
def get_all_messages():
    results = Message.query.all()
    # print(courses)
    return json.dumps(results, default=Message.to_json)


@api_blueprint.route('/message/set/<int:msg_id>', methods=['PUT'])
def set_message_status(msg_id):
    if request.values.get('status') is None:
        return json.dumps({
            'status': 'error',
            'msg': 'status is missing'
        }), 400
    status = request.values.get('status')
    row = Message.query.filter(Message.Message_id == msg_id).first()
    if row is None:
        return json.dumps({
            'status': 'error',
            'msg': 'target message is not found'
        }), 404
    row.Message_send = status
    try:
        db.session.commit()
    except Exception as e:
        print(e)
        return json.dumps({
            'status': 'error',
            'msg': 'db operation error'
        }), 500
    return json.dumps({
        'status': 'success'
    })


@api_blueprint.route('/message', methods=['POST'])
def add_message():
    user_id = request.values.get('User_id')
    cos_id = request.values.get('Cos_id')
    message = request.values.get('Message')
    message_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
    message_send = 0

    if user_id is None or cos_id is None or message is None:
        return json.dumps({
            'status': 'error',
            'msg': 'param is missing'
        }), 400

    row = Message()
    row.User_id = user_id
    row.Cos_id = cos_id
    row.Message = message
    row.Message_time = message_time
    row.Message_send = message_send

    db.session.add(row)
    try:
        db.session.commit()
    except Exception as e:
        print(e)
        return json.dumps({
            'status': 'error',
            'msg': 'db operation error'
        }), 500
    return json.dumps({
        'status': 'success'
    })

